package com.liuhouse.service.impl;

import com.liuhouse.dao.StudentMapper;
import com.liuhouse.model.Student;
import com.liuhouse.service.StudentService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;

/**
 * 使用dubbo中的注解暴露服务
 */
@DubboService(interfaceClass = StudentService.class , version = "1.0" , timeout = 5000)
//这里实现的是公共资源中的接口
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentMapper studentMapper;

    //对redis进行注入
    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 添加学生
     * 0:添加失败
     * 1:添加成功
     * 2:学生已经存在
     * 3:传递过来的学生电话为空
     * @param student
     * @return
     */

    /**
     * @param student
     * @return
     */

    @Override
    public int addStudent(Student student) {
        Integer result = 0;
        if (student != null) {
            //查看学生是否存在
            Student studentFind = studentMapper.selectStudentByPhone(student.getPhone());
            //从数据库中已经查找到学生
            if (studentFind != null) {
                result = 2;
            } else {
                result = studentMapper.addStudentByData(student);
            }
        } else {
            //学生电话为空
            result = 3;
        }
        return result;
    }

    @Override
    public Student queryStudent(Integer id) {
        //设置键为字符串类型
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //值存储为json
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<Student>(Student.class));
        Student student = null;
        final String USER_KEY = "STUDENT:";
        if(id != null){
           String key = USER_KEY + id;
            System.out.println("从redis中去查询");
            student = (Student) redisTemplate.opsForValue().get(key);
           //如果没有在缓存中查找到数据
           if(student == null){
               //就要去mybatis进行查询
               System.out.println("从数据库中去查询");
               student = studentMapper.selectStudentById(id);
               //如果从数据库中查询出了学生的数据
               if(student != null){
                    //存储到redis
                   redisTemplate.opsForValue().set(key , student);
               }else{
                   redisTemplate.opsForValue().set(key , Student.defaultStudent());
               }
           }
        }
        return student;
    }
}
